package com.shuwen.gcdj.job;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shuwen.gcdj.bean.message.response.PLCAlarmMessageResp;
import com.shuwen.gcdj.common.constant.Constants;
import com.shuwen.gcdj.common.exception.ApiException;
import com.shuwen.gcdj.common.util.RandomUtil;
import com.shuwen.gcdj.entity.*;
import com.shuwen.gcdj.entity.basics.BasicsEquipment;
import com.shuwen.gcdj.entity.basics.OrderMaintenanceorder;
import com.shuwen.gcdj.entity.basics.OrderMaintenanceorderdetail;
import com.shuwen.gcdj.entity.basics.OrderMaintenanceorderflow;
import com.shuwen.gcdj.mapper.mysql.*;
import com.shuwen.gcdj.mapper.mysql.basics.BasicsEquipmentMapper;
import com.shuwen.gcdj.mapper.mysql.basics.OrderMaintenanceorderMapper;
import com.shuwen.gcdj.mapper.mysql.basics.OrderMaintenanceorderdetailMapper;
import com.shuwen.gcdj.mapper.mysql.basics.OrderMaintenanceorderflowMapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author :yys
 * 根据计划生成维保工单
 * @date : 2023/5/10 14:16
 */
@Component
@Slf4j
public class PlancyclemanagementScheduled {


    @Autowired
    private OrderMaintenanceorderflowMapper orderMaintenanceorderflowMapper;

    @Autowired
    private OrderMaintenanceorderMapper orderMaintenanceorderMapper;

    @Autowired
    private OrderMaintenanceorderdetailMapper orderMaintenanceorderdetailMapper;

    @Autowired
    private PlanDetailMapper planDetailMapper;

    @Autowired
    private BasicsEquipmentMapper basicsEquipmentMapper;

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private StrategyInspectionitemtemplaterelMapper strategyInspectionitemtemplaterelMapper;

    @Autowired
    private BasicsStructureMapper basicsStructureMapper;

    /**
     * 每天凌晨0点执行
     */
    @XxlJob("plancyclemanagementScheduled")
    public void autoexecutecreatemaintainorder() throws Exception{
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        LambdaQueryWrapper<StrategyPlandetail> queryWrapper = new LambdaQueryWrapper<>();
        Date date = new Date();
        String dates = sd.format(date);
        queryWrapper.eq(StrategyPlandetail::getExecDate,dates)
                .eq(StrategyPlandetail::getIsDelete, Constants.IS_DELETE_NORMAL)
                .groupBy(StrategyPlandetail::getEquipmentId,
                        StrategyPlandetail::getMajor,
                        StrategyPlandetail::getMaintenanceType,
                        StrategyPlandetail::getUserId);
        List<StrategyPlandetail> strategyPlandetails = planDetailMapper.selectList(queryWrapper);
        for(StrategyPlandetail s : strategyPlandetails){
            LambdaQueryWrapper<OrderMaintenanceorder> queryWrapperOrder = new LambdaQueryWrapper<>();
            queryWrapperOrder.eq(OrderMaintenanceorder::getStartDate,sd.format(date))
                    .eq(OrderMaintenanceorder::getIsDelete, Constants.IS_DELETE_NORMAL)
                    .orderByDesc(OrderMaintenanceorder::getOrderCode)
                    .last("limit 1");
            OrderMaintenanceorder orderMaintenanceorderOne = orderMaintenanceorderMapper.selectOne(queryWrapperOrder);
            LambdaQueryWrapper<BasicsEquipment> queryWrapperBa = new LambdaQueryWrapper<>();
            queryWrapperBa.eq(BasicsEquipment::getId,s.getEquipmentId())
                    .eq(BasicsEquipment::getIsDelete,Constants.IS_DELETE_NORMAL);
            BasicsEquipment basicsEquipment = basicsEquipmentMapper.selectOne(queryWrapperBa);
            if(basicsEquipment == null){
                throw new ApiException("设备不存在");
            }
            LambdaQueryWrapper<Account> queryWrapperUser = new LambdaQueryWrapper<>();
            queryWrapperUser.eq(Account::getId,s.getUserId())
                    .eq(Account::getIsDelete,Constants.IS_DELETE_NORMAL);
            Account account = accountMapper.selectOne(queryWrapperUser);
            if(account == null){
                throw new ApiException("维保人不存在");
            }
            LambdaQueryWrapper<Department> queryWrapperDept = new LambdaQueryWrapper<>();
            queryWrapperDept.eq(Department::getId,account.getDeptId())
                    .eq(Department::getIsDelete,Constants.IS_DELETE_NORMAL);
            Department sysDictionary = new Department();
            Department department = sysDictionary.selectOne(queryWrapperDept);
            if(department == null){
                throw new ApiException("部门不存在");
            }
            OrderMaintenanceorder orderMaintenanceorder = new OrderMaintenanceorder();
            BeanUtil.copyProperties(s,orderMaintenanceorder);
            orderMaintenanceorder.setId(null);
            orderMaintenanceorder.setCreateId(s.getUserId());
            orderMaintenanceorder.setUpdateId(s.getUserId());
            orderMaintenanceorder.setOrderCode(RandomUtil.WbCode(orderMaintenanceorderOne == null ? "" : orderMaintenanceorderOne.getOrderCode()));
            orderMaintenanceorder.setEquipmentId(s.getEquipmentId());
            orderMaintenanceorder.setEquipmentName(basicsEquipment.getName());
            orderMaintenanceorder.setType(s.getMaintenanceType());
            orderMaintenanceorder.setResponsibleDepartment(department.getId());
            String format = sd.format(date);
            orderMaintenanceorder.setStartDate(sd.parse(format));
            orderMaintenanceorder.setState(1);
            orderMaintenanceorder.setCreateId(account.getId());
            orderMaintenanceorder.setUpdateId(account.getId());
            orderMaintenanceorder.setResponsibleUserid(s.getUserId());
            orderMaintenanceorderMapper.insert(orderMaintenanceorder);
            createOrderMain(s,orderMaintenanceorder,dates);
            OrderMaintenanceorderflow orderMaintenanceorderflow = new OrderMaintenanceorderflow();
            BeanUtil.copyProperties(orderMaintenanceorder,orderMaintenanceorderflow);
            orderMaintenanceorderflow.setOrderId(orderMaintenanceorder.getId());
            orderMaintenanceorderflow.setOrderState(1);
            orderMaintenanceorderflow.setOperatorType(1);
            orderMaintenanceorderflow.setId(null);
            orderMaintenanceorderflowMapper.insert(orderMaintenanceorderflow);
            orderMaintenanceorderflow.setId(null);
            orderMaintenanceorderflow.setOperator(orderMaintenanceorder.getResponsibleUserid());
            orderMaintenanceorderflow.setOperatorType(2);
            orderMaintenanceorderflowMapper.insert(orderMaintenanceorderflow);
        }
    }

        public void createOrderMain(StrategyPlandetail s,OrderMaintenanceorder orderMaintenanceorder,String date){
            LambdaQueryWrapper<StrategyPlandetail> queryWrapperTwo = new LambdaQueryWrapper<>();
            queryWrapperTwo.eq(StrategyPlandetail::getIsDelete,Constants.IS_DELETE_NORMAL)
                    .eq(StrategyPlandetail::getEquipmentId,s.getEquipmentId())
                    .eq(StrategyPlandetail::getMaintenanceType,s.getMaintenanceType())
                    .eq(StrategyPlandetail::getExecDate,date)
                    .eq(StrategyPlandetail::getMajor,s.getMajor())
                    .eq(StrategyPlandetail::getUserId,s.getUserId());
            List<StrategyPlandetail> sList = planDetailMapper.selectList(queryWrapperTwo);
            LambdaQueryWrapper<StrategyInspectionitemtemplaterel> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(StrategyInspectionitemtemplaterel::getIsDelete,Constants.IS_DELETE_NORMAL)
                    .in(StrategyInspectionitemtemplaterel::getTemplateId,sList.stream().map(StrategyPlandetail::getItemTempId).collect(Collectors.toList()))
                    .in(StrategyInspectionitemtemplaterel::getStructureId,sList.stream().map(StrategyPlandetail::getSecondStructureId).collect(Collectors.toList()));
            List<StrategyInspectionitemtemplaterel> strategyInspectionitemtemplaterelList = strategyInspectionitemtemplaterelMapper.selectList(queryWrapper);
            if(CollectionUtils.isEmpty(strategyInspectionitemtemplaterelList)){
                return;
            }
            List<OrderMaintenanceorderdetail> orderMaintenanceorderdetailList = new ArrayList<>();
            for(StrategyPlandetail ss : sList){
                List<StrategyInspectionitemtemplaterel> itemRelList = strategyInspectionitemtemplaterelList.stream().filter(p -> p.getTemplateId().equals(ss.getItemTempId()) && p.getStructureId().equals(ss.getSecondStructureId())).collect(Collectors.toList());
                for(StrategyInspectionitemtemplaterel sip : itemRelList){
                    OrderMaintenanceorderdetail orderMaintenanceorderdetail = new OrderMaintenanceorderdetail();
                    BeanUtil.copyProperties(s,orderMaintenanceorderdetail);
                    orderMaintenanceorderdetail.setId(null);
                    orderMaintenanceorderdetail.setOrderId(orderMaintenanceorder.getId());
                    orderMaintenanceorderdetail.setState(null);
                    orderMaintenanceorderdetail.setCreateId(s.getUserId());
                    orderMaintenanceorderdetail.setUpdateId(s.getUserId());
                    orderMaintenanceorderdetail.setCreateTime(null);
                    orderMaintenanceorderdetail.setFirstStructureId(ss.getFirstStructureId());
                    orderMaintenanceorderdetail.setSecondStructureId(ss.getSecondStructureId());
                    orderMaintenanceorderdetail.setPlanCycleType(ss.getPlanCycleType());
                    orderMaintenanceorderdetail.setOrderCode(orderMaintenanceorder.getOrderCode());
                    orderMaintenanceorderdetail.setInspectionItemId(sip.getInspectionItemId());
                    orderMaintenanceorderdetailList.add(orderMaintenanceorderdetail);
                }
            }
            if (orderMaintenanceorderdetailList.size() <= 1) {
                orderMaintenanceorderdetailMapper.addBatch(orderMaintenanceorderdetailList);
            } else {
                int totallCount = orderMaintenanceorderdetailList.size();
                int pages = getCeiling(totallCount, 1);
                for (int i = 1; i <= pages; i++) {
                    List<OrderMaintenanceorderdetail> thisbatch = orderMaintenanceorderdetailList.stream().skip((i - 1) * 1L).limit(1).collect(Collectors.toList());
                    orderMaintenanceorderdetailMapper.addBatch(thisbatch);
                }
            }
        }

    /**
     * 分页
     * @param count 总条数
     * @param size 单页数据
     * @return
     */
    public static Integer getCeiling(Integer count, Integer size) {
        if (count == 0 || size == 0) {
            return 0;
        }
        double value = Double.valueOf(count) / Double.valueOf(size);
        return count > 0 ? (int)Math.ceil(value) : 0;
    }

}
